﻿using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using System.Data;
using Extensions;
using System.Drawing;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid;

namespace eFatura.Utility.Grid
{
    public partial class ColumnFocuser : XPopupForm
    {
        private GridView GridView;

        public ColumnFocuser(GridView GridView)
        {
            InitializeComponent();

            this.GridView = GridView;
            DataTable dt = new DataTable("Columns");
            dt.Columns.Add("Column Name", typeof(string));
            dt.Columns.Add("Index", typeof(int));

            foreach (GridColumn col in GridView.VisibleColumns)
            {
                DataRow dr = dt.NewRow();
                dr["Column Name"] = (col.Caption == "" ? col.FieldName : col.Caption);
                dr["Index"] = col.AbsoluteIndex;
                dt.Rows.Add(dr);
            }

            gvColumnFocuser.Init(dt);
            gvColumnFocuser.MakeReadOnly();
            gvColumnFocuser.MakeRowSelectable();
            gvColumnFocuser.DoubleClick += gv_DoubleClick;
            gvColumnFocuser.MakeColumnInvisible("Index");
            gvColumnFocuser.BestFitColumns();

            gvColumnFocuser.FocusedRowHandle = GridControl.AutoFilterRowHandle;
            gvColumnFocuser.KeyDown += gv_KeyDown;
        }

        void gv_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && gvColumnFocuser.DataRowCount == 1)
            {
                SelectedColumnIndex = (int)gvColumnFocuser.GetDataRow(gvColumnFocuser.GetVisibleRowHandle(0))["Index"];
                e.Handled = true;
                this.DialogResult = DialogResult.OK;
            }
            else if (e.KeyCode == Keys.Escape)
            {
                this.DialogResult = DialogResult.Cancel;
            }
            else
            {
                e.Handled = false;
            }
        }

        void gv_DoubleClick(object sender, System.EventArgs e)
        {
            Point pt = gc.PointToClient(Control.MousePosition);
            GridHitInfo info = gvColumnFocuser.CalcHitInfo(pt);
            if (info.RowHandle > -1)
            {
                SelectedColumnIndex = (int)gvColumnFocuser.GetFocusedRowCellValue("Index");
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
        }

        public int SelectedColumnIndex { get; set; }
    }
}